<script setup lang="tsx">
import {ref} from "vue";
import {useBoolean, useLoading} from "~/packages/hooks";
import {$t} from "@/locales";
import {DataTableBaseColumn, NButton, NPopconfirm} from "naive-ui";
import {useAppStore} from "@/store/modules/app";
import {fetchCompanyPage, fetchCompanyUserCount} from "@/service/api/tenant";

import TenantOperateDrawer from "./tenant-operate-drawer.vue";
import TenantInfo from "@/views/tenant/tenant-info.vue";

const appStore = useAppStore();
const {loading} = useLoading();
const operateType = ref<Api.Common.OperateType>('add');
const {bool: drawerVisible, setTrue: openDrawer} = useBoolean();
const editingData = ref<Api.Entity.Company | null>(null);
const data = ref<Api.Entity.Company[]>([]);
const checkedRowKeys = ref<string[]>([]);
const searchKeyword = ref('');
const searchParams = ref<Api.Common.Pageable>({
  filters: null,
  orderDirection: null,
  orderProperty: null,
  pageNumber: 1,
  pageSize: 15,
  searchProperty: null,
  searchValue: null
});
const pagination = ref({
  pageSize: 15,
  pageNumber: 1,
  searchProperty: null,
  searchValue: null,
  orderProperty: null,
  orderDirection: null,
  filters: null
});
const columns = ref([
  {
    key: 'name',
    title: '公司名称',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'email',
    title: '邮箱',
    align: 'center',
  },
  {
    key: 'address',
    title: '地址',
    align: 'center',
  },
  {
    key: 'phone',
    title: '联系电话',
    align: 'center',
  },
  {
    key: 'params.userCount',
    title: '用户数',
    align: 'center',
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    render: row => (
      <div class="flex-center gap-8px">
        <NButton ghost size="small" onClick={() => handleView(row.id)}>
          查看
        </NButton>
        <NButton type="primary" ghost size="small" onClick={() => handleEdit(row.id)}>
          {$t('common.edit')}
        </NButton>
        <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
]);
const showModal = ref(false);

async function getData() {
  let res = await fetchCompanyPage(searchParams.value);
  data.value = res.data?.content || [];
  for (const re of data.value || []) {
    fetchCompanyUserCount({
      id: re.id
    }).then(res => {
      re.params.userCount = res.data
    })
  }
}

function handleAdd() {
  operateType.value = 'add';
  openDrawer();
}

function handleEdit(id: number) {
  operateType.value = 'edit';
  editingData.value = data.value.find(item => item.id === id) || null;
  openDrawer();
}

function handleView(id: number) {
  showModal.value = true;
}

async function handleDelete(id: number) {
  window.$message?.success($t('common.deleteSuccess'));
  await getData();
}

function renderCell(value: any, rowData: Api.Entity.Company, column: DataTableBaseColumn) {
  return value
}

function handleSearch() {
  if (searchKeyword.value.trim() === '') {
    searchParams.value.filters = []
  } else {
    let val = '%' + searchKeyword.value + '%';
    searchParams.value.filters = [
      {
        operator: 'or',
        filters: [
          {
            property: 'name',
            value: val,
            operator: 'like',
          },
          {
            property: 'email',
            value: val,
            operator: 'like',
          },
          {
            property: 'address',
            value: val,
            operator: 'like',
          },
          {
            property: 'phone',
            value: val,
            operator: 'like',
          },
        ]
      }
    ]
  }

  getData()
}

function closeModal() {

  showModal.value = false
}

getData();

</script>

<template>
  <div class="flex-vertical-stretch gap-16px overflow-hidden <sm:overflow-auto">
    <NCard title="" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden"
           content-style="padding: .5rem !important;">
      <template #header>
        <n-grid x-gap="12" :cols="2">
          <n-gi>
            <NSpace wrap justify="start" class="<sm:w-200px">
              <n-input-group>
                <n-input :style="{ width: '100%' }" v-model:value="searchKeyword" placeholder="输入关键字搜索"/>
                <n-button type="primary" @click="handleSearch">
                  <icon-material-symbols-search class="text-icon"/>
                  搜索
                </n-button>
              </n-input-group>
            </NSpace>
          </n-gi>
          <n-gi>
            <NSpace wrap justify="end" class="<sm:w-200px">
              <NButton type="success" @click="handleAdd">
                <template #icon>
                  <icon-ic-round-plus class="text-icon"/>
                </template>
                {{ $t('common.add') }}
              </NButton>
              <NButton @click="getData">
                <template #icon>
                  <icon-mdi-refresh class="text-icon" :class="{ 'animate-spin': loading }"/>
                </template>
                {{ $t('common.refresh') }}
              </NButton>
            </NSpace>
          </n-gi>
        </n-grid>
      </template>
      <NDataTable
        :bordered="false"
        :single-line="false"
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="640"
        :loading="loading"
        :pagination="pagination"
        :row-key="item => item.id"
        :render-cell="renderCell"
        class="sm:h-full"
      />
      <TenantOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
    <n-modal v-model:show="showModal">
      <n-card
        style="width: 1000px"
        title="查看租户信息"
        :bordered="true"
        size="huge"
        role="dialog"
        aria-modal="true"
        header-style="padding:5px 5px 5px 8px !important;background-color:#f4f6f9"
        content-style="padding:5px .5rem .5rem  !important;background-color:#f4f6f9"
      >
        <template #header-extra>
          <n-button quaternary circle @click="closeModal">
            <template #icon>
              <icon-material-symbols-close-rounded class="text-18px"/>
            </template>
          </n-button>

        </template>
        <template #default>
          <TenantInfo/>
        </template>
        <template #footer>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<style scoped>

</style>
